package yxy.game.pm2.command.conquest;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankWorship;
import yxy.game.pm2.bean.module.rank.RankWorshipPlayer;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ConquestMessage;
import yxy.game.pm2.module.conquest.RankConquest;
import yxy.game.pm2.module.player.PlayerHandle;

import java.util.Collection;

/** 征战 通关进度排行榜 */
@MessageType(proto = Command.ConquestProgressRank, classtype = ConquestMessage.ConquestProgressRankRequest.class)
public class CMD_ConquestProgressRank extends Command<ConquestMessage.ConquestProgressRankRequest> {

	@Override
	public void execute(MessageSource messageSource, ConquestMessage.ConquestProgressRankRequest request) {
		String playerCode = messageSource.getTag();

		ConquestMessage.ConquestProgressRankResponse.Builder response = ConquestMessage.ConquestProgressRankResponse.newBuilder();

		RankConquest rankConquest = RankConquest.getRank(playerCode);
		try {

			RankWorship worship = rankConquest.getWorship();
			RankWorshipPlayer worshipPlayer = RankWorshipPlayer.get(playerCode, worship);

			
			Collection<RankEntry> top = rankConquest.top(rankConquest.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int floor = entry.getValue().intValue();

				ConquestMessage.RankConquest.Builder builder = ConquestMessage.RankConquest.newBuilder();

				builder.setRank(++rank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(pCode));
				builder.setMapId(floor);
				builder.setFans(worship.getScore(pCode));
				builder.setLiked(worshipPlayer.getWorshiped().contains(pCode));
				response.addRank(builder);
			}

			{
				int playerRank = 0;
				int mapId = 0;
				RankEntry entry = rankConquest.get(playerCode);
				if (entry != null) {
					playerRank = rankConquest.rank(playerCode);
					mapId = entry.getValue().intValue();
				}

				ConquestMessage.RankConquest.Builder builder = ConquestMessage.RankConquest.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(playerCode));
				builder.setMapId(mapId);
				response.setMy(builder);
			}
			
			response.setTimes(worshipPlayer.remainTimes());

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}

	}

	private void send(MessageSource messageSource, ConquestMessage.ConquestProgressRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}